package com.ruijie.acl.task.config;

import java.util.Date;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.springframework.util.Assert;

import com.ruijie.acl.utils.AclConfigUtil;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.batch.core.factory.SpringConfigAware;
import com.ruijie.batch.plan.PlanParameters;
import com.ruijie.batch.task.ItemProcessResult;
import com.ruijie.emp.batch.task.AbstractDeviceTasklet;
import com.ruijie.emp.device.Device;
import com.ruijie.emp.system.service.TelnetTemplateService;
import com.ruijie.emp.task.EMPTaskDomain;
import com.ruijie.emp.task.util.TaskUtil;
import com.ruijie.foundation.adapter.Adapter;
import com.ruijie.foundation.adapter.AdapterDomain;
import com.ruijie.foundation.adapter.parameter.ParameterExecutor;
import com.ruijie.foundation.adapter.utils.Dom4jUtil;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.network.model.TelnetParameter;

/**
 * 
 * <p>Title: TaskConfigPEGlobal         </p>
 * <p>Description: PE 全局配置 </p>
 * <p>Copyright: Copyright (c) 2008     </p>
 * <p>Company: Ruijie Co., Ltd.       </p>
 * <p>Create Time: 2009-7-14           </p>
 * @author chenxiaoyuer
 * <p>Update Time:                      </p>
 * <p>Updater:                          </p>
 * <p>Update Comments:                  </p>
 */
public class TaskTestAbsoluteTimeInfo extends AbstractDeviceTasklet implements SpringConfigAware {
    private Log logger = LogFactory.getLog(TaskTestAbsoluteTimeInfo.class);

    protected TelnetTemplateService service;

    public TelnetTemplateService getService() {
        return service;
    }

    public void setService(TelnetTemplateService service) {
        this.service = service;
    }

    @SuppressWarnings("unchecked")
    public ItemProcessResult processItem(Object item, PlanParameters parameters) {
        ItemProcessResult result = new ItemProcessResult();

        Assert.notNull(item, "item is null");

        Device device = (Device) item;

        if (device.getTelnetTemplate() == null) {
            if (service != null) {
                logger.warn("device.getTelnetTemplate() is null.");
                device.setTelnetTemplate(service.getDefault());
            }
            if (device.getTelnetTemplate() == null) {
                result.setSuccess(false);
                result.setException(new BusinessException(EMPTaskDomain.EMP_TASK_PARA_TELNETTEMPLOST));
                return result;
            }
        }

        TelnetParameter telnetParameter = TaskUtil.loadTelnetParameter(device, true);

        ParameterExecutor pe = new ParameterExecutor();
        HashMap para = new HashMap(parameters.getParameters());

        String conn = TaskUtil.tranTelnetConnStr(telnetParameter);

        pe.setupInterfaceInfo(TaskUtil.getDeviceSimpleCode(device, "SwitchTelnet"), "");
        pe.setupTargetSystem("", "", "SwitchTelnet", device.getAdminIp(), "" + telnetParameter.getPort(), "", "", conn,
                telnetParameter.getUser(), telnetParameter.getPassword(), "false");
        pe.setupProtocol("", "", "SwitchTelnet", "", "" + telnetParameter.getTimeout(), "", "", "", "", "", "0");

        String cmdPrompt = telnetParameter.isNeedSuPassword() //
        ? telnetParameter.getSuPrompt()
                : telnetParameter.getPrompt();

        String[] errs = { "Invalid input detected", //
				"Incomplete command", //
				"Unrecognized command", //
				"Incomplete command", //
				"Bad ACL",//
				"Acl Mode Not Match",//
				"Cannot delete given timerange mode currently",//		
				"Input is invalid", //
				"for the entry is existed", 
				"Name is too long", 
				"not supported by device" };
        String cmdErrorStr = TaskUtil.array2str(errs, "|");
        String cmdDoneFlag = cmdPrompt;
        String cmdSuccFlag = cmdPrompt;

        String cmdConfigEnd = "config\\)" + cmdPrompt.charAt(cmdPrompt.length() - 1);
        String cmdEnd = "\\)" + cmdPrompt.charAt(cmdPrompt.length() - 1);
        // 开始设置命令
        pe.addCommand(pe.buildCommandOperate("configure terminal", cmdConfigEnd, cmdConfigEnd, null));

        String timeRangeName = "test" + AclUtil.createUniqueID();
        // 删除时间段
		pe.addCommand(pe.buildCommandOperate("no time-range " + timeRangeName , cmdEnd, cmdEnd, null));
		// 添加时间段
		pe.addCommand(pe.buildCommandOperate("time-range " + timeRangeName, cmdErrorStr + cmdEnd, cmdEnd,
				null));
		
		// 是否支持月份为January的模式
		String absoluteString = "absolute start " + AclConfigUtil.getAbsoluteDateString(new Date(), true);
		
		pe.addCommand(pe.buildCommandOperate(absoluteString, 
				cmdErrorStr + cmdEnd,cmdEnd, null));
        // 删除时间段
		pe.addCommand(pe.buildCommandOperate("no time-range " + timeRangeName , cmdEnd, cmdEnd, null));
		
        // 
        pe.addCommand(pe.buildCommandOperate("end", cmdDoneFlag, cmdSuccFlag, new HashMap[] { para }));
        pe.addCommand(pe.buildCommandOperate("write", cmdDoneFlag, cmdSuccFlag, new HashMap[] { para }));

        try {
            Adapter adpater = new Adapter();
            Document doc = pe.getParameter();
            if (logger.isDebugEnabled()){
                logger.debug(Dom4jUtil.generateXMLStringBuffer(doc, null));
            }
            String r = (String) adpater.execute(doc);

            doc = Dom4jUtil.createDOM4jDocument(r, false, null);

            String succ = doc.getRootElement().selectSingleNode("isSuccess").getText();
            String code = doc.getRootElement().selectSingleNode("resultCode").getText();
            String desc = doc.getRootElement().selectSingleNode("workOrderDesc").getText();

            result.setExecuted(succ.equals("true"));
            result.setSuccess(code.equals("true"));

            if (!result.getSuccess())
                TaskUtil.buildBusinessException(//
                        !result.getExecuted(), code.equals("retry"), !result.getSuccess(), desc);
            else
                result.setDescription(AdapterDomain.ADAPTER_EXECUTE_SUCCESS, new String[] {});

            return result;
        } catch (BusinessException e) { // 业务异常抛出
        	if (e.getMessage().equals("adapter_execute_error_business")){
        		// 删除临时时间段
              cmdConfigEnd = "config\\)" + cmdPrompt.charAt(cmdPrompt.length() - 1);
              cmdEnd = "\\)" + cmdPrompt.charAt(cmdPrompt.length() - 1);
              ParameterExecutor pe1 = new ParameterExecutor();
              pe1.setupInterfaceInfo(TaskUtil.getDeviceSimpleCode(device, "SwitchTelnet"), "");
              pe1.setupTargetSystem("", "", "SwitchTelnet", device.getAdminIp(), "" + telnetParameter.getPort(), "", "", conn,
                      telnetParameter.getUser(), telnetParameter.getPassword(), "false");
              pe1.setupProtocol("", "", "SwitchTelnet", "", "" + telnetParameter.getTimeout(), "", "", "", "", "", "0");
              // 开始设置命令
              pe1.addCommand(pe1.buildCommandOperate("configure terminal", cmdConfigEnd, cmdConfigEnd, null));

              // 删除时间段
              pe1.addCommand(pe1.buildCommandOperate("no time-range " + timeRangeName , cmdEnd, cmdEnd, null));
              Adapter adpater = new Adapter();
              Document doc = pe1.getParameter();
              try{
            	  adpater.execute(doc);
              }catch(Exception ex){
            	  //
              }
        	}else{
        		throw e;
        	}
        } catch (Exception e) {
            logger.error("TaskTestAbsoluteTimeInfo error.", e);
        }

        return null;
    }

}
